package jwt

import (
	"gin-blog/utils/errcode"
	"gin-blog/utils/helper"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var data = make(map[string]interface{})
		var code = errcode.SUCCESS
		//token := c.Query("token")
		token := c.Request.Header.Get("token")

		if token == "" {
			code = errcode.ERROR_AUTH_CHECK_TOKEN_FAIL
		} else {
			claims, err := helper.ParseToken(token)
			if err != nil {
				code = errcode.ERROR_AUTH_CHECK_TOKEN_FAIL
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = errcode.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
			}
		}

		if code != errcode.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code" : code,
				"msg" : errcode.GetMsg(code),
				"data" : data,
			})
			c.Abort()
			return
		}
		c.Next()
	}
}